import Vue from 'vue'
import VueRouter from 'vue-router'

// 在VueRouter上配置路由跳转，在router中的index.js中加上以下代码，注意加在use之前
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return routerPush.call(this, location).catch(err => {
    console.log("开发者声明：此错误暂时可以忽略"+err)
  })
};

Vue.use(VueRouter)

const routes = [
  {
    path: '/RootPage',
    name: 'RootPage',
    component:() => import('../views/RootPage.vue'),
    redirect: { name: 'HomePage' },
    children:[
      {
        path: '/HomePage',
        name: 'HomePage',
        component:() => import('../views/HomePage.vue'),
      },
      {
        path: '/UserPage',
        name: 'UserPage',
        component:() => import('../views/UserPage.vue'),
        meta: {requiresAuth: true,},
      },
    ]
  },

  {
    path: '/TermsPage',
    name: 'TermsPage',
    component:() => import('../components/TermsPage.vue'),
  },

  {
    path: '/RegisterPage',
    name: 'RegisterPage',
    component:() => import('../views/RegisterPage.vue'),
  },

  {
    path: '/LoginPage',
    name: 'LoginPage',
    component:() => import('../views/LoginPage.vue')
  },

  {//重定向，默认访问/HomePage
    path: '/',
    redirect:'/RootPage'
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 检查是否需要进行认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查是否存在 JWT 令牌
    if (!localStorage.getItem('orange_supermarket')) {
      // 如果没有 JWT 令牌,则跳转到登录页面
      next('/LoginPage')
    } else {
      // 如果有 JWT 令牌,则继续导航
      next()
    }
  } else {
    // 如果不需要认证,则继续导航
    next()
  }
})

export default router
